package datastruct.uf;

/**
 * @author RunningShrimp
 * @date 2021/5/28  17:24
 * @see <a href=""></a>
 */
public class QuickUnionFindBySize implements UnionFind {
    private final int[] parent;

    private final int[] sizes;

    public QuickUnionFindBySize(int size) {
        parent = new int[size];
        sizes = new int[size];
        for (int i = 0; i < parent.length; i++) {
            parent[i] = i;
            sizes[i] = 1;
        }
    }

    @Override
    public int getSize() {
        return parent.length;
    }

    private int find(int p) {
        if (p < 0 || p > parent.length) {
            throw new IndexOutOfBoundsException("索引无效");
        }
        while (p != parent[p]) {
            p = parent[p];
        }
        return p;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElements(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);

        if (pRoot == qRoot) {
            return;
        }
        //根据两个元素所在树的元素个数不同判断合并方向
        //将元素个数少的集合合并到元素个数多的集合上
        if(sizes[pRoot]<sizes[qRoot]) {
            parent[pRoot] = qRoot;
            sizes[qRoot] += sizes[pRoot];
        }else{
            parent[qRoot] = pRoot;
            sizes[pRoot] += sizes[qRoot];
        }
    }
}
